package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.206.130");  // wht6.cn
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection(); // 连接
        Channel c = con.createChannel();    // 通信的通道
        // 创建队列
        c.queueDeclare("task_queue",true,false,false,null);

        // 创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到："+s);
                //模拟处理耗时消息
                //遍历字符串，每找到一个'.'字符，暂停1秒
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == '.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                //手动发送回执
                // c.basicAck(回执, 是否同时确认之前接收过的所有消息);
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("------------------------消息处理完成");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        // 每次收一条，处理完之前不收下一条
        c.basicQos(1);

        // 接收消息
        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);
    }
}
